/*
 * JQuery zTree Combox v1.0.0
 * 代码是基于zTree的扩展，引用前请先引用zTree的相关文件
 *
 * Copyright (c) 2017 Solin
 *
 * Licensed same as jquery - MIT License
 * http://www.opensource.org/licenses/mit-license.php
 *
 * email: solin.bamboo@gmail.com
 * Date: 2017-07-12
 */

(function ($) {
	$.fn.comboboxTree = function (options) {
    	if (typeof options == 'object' || !options) {
    		return methods.init.apply(this, arguments);
    	} else {
    		return methods[options].apply(this, Array.prototype.slice.call(arguments, 1));
    	}
    };
	var methods = {
		init: function(options){
			var defaults = {
					url: '', //请求数据的URL地址
					param: [], //请求参数
		    		idKey: 'id', //下拉框树节点id
			        pIdKey: 'pId', //下拉框树节点父id
			        rootPId: "0", //根节点值
			        nameKey: 'name', //文本key
			        defaultValue: null //默认值
		        }
	        options = $.extend(defaults, options);
	    	//菜单树Tree Setting 
			var setting = {
				view: {
					dblClickExpand: false
				},
				data: {
			            simpleData: {
			             enable: true,
			             idKey: 'id',
			             pIdKey: 'pId',
			             rootPId: options.rootPId 
			         } 
			    },
				callback: {
					onClick: __onClick
				}
			}; 
			var comboxTreeId = this.attr('id'); 
			
			var $combTree = $('#'+comboxTreeId);
			$combTree.attr({ readonly: 'true','bind-data': '' }).css({'cursor':'pointer','background-color': '#fff'}).addClass("form-control");
			var $carset = $('<span style="position:absolute;left:'+($combTree.outerWidth()-15)+'px; bottom:15px;" class="caret"></span>');
			$combTree.after($carset);
			//创建一个可以用于form表单提交的隐藏标签
			var combTreeNameAttr = $combTree.attr('name');
			if(combTreeNameAttr) {
				$combTree.removeAttr('name');
				var $combTreeInput = $('<input type="hidden" name="'+combTreeNameAttr+'"/>');
				$combTree.after($combTreeInput);
			}
			var setDefault = function(){
				//set text
				$('#'+comboxTreeId).val(options.defaultText);
				//set code
				$('#'+comboxTreeId).attr('bind-data', options.defaultValue);
				if (combTreeNameAttr){
					$('input[name="'+combTreeNameAttr+'"]').val(options.defaultValue);
				};
			}
			//设置文本框默认值
			if (options.defaultValue){
				getTreeData(options);
				setDefault();
			}
			//zTree Node 的点击事件
			function __onClick(e, treeId, treeNode) { 
				//获取选中的节点的text 和 code
				var zTreeId = $(".menuContent").find('ul').attr('id');
				var zTree = $.fn.zTree.getZTreeObj(zTreeId),
				nodes = zTree.getSelectedNodes(),
				name = "", id = "";
				nodes.sort(function compare(a,b){return a.id-b.id;});
				for (var i=0, l=nodes.length; i<l; i++) {
					name += nodes[i].name + ",";
					id += nodes[i].id + ",";
				}
				if (id.length > 0 ) id = id.substring(0, id.length-1);
				if (name.length > 0 ) name = name.substring(0, name.length-1);
				//set text
				$('#'+comboxTreeId).val(name);
				//set code
				$('#'+comboxTreeId).attr('bind-data', id);
				if (combTreeNameAttr){
					$('input[name="'+combTreeNameAttr+'"]').val(id);
				} 
				//销毁下拉框容器
				$(".menuContent").remove();
				if(options.func) {
				    options.func.call();
				}
			}
			
			$('body').on('click', function(e){   
				if (e.target.id == comboxTreeId) {
					if($(".menuContent").length == 0) {
						//动态创建下拉框容器
						var $ztreeContent = $('<div class="menuContent" style="display:block; position: absolute;background:#FFF; max-height: 440px; overflow-x: hidden;border: 1px solid #ccc;z-index:99;"></div>');			
						var treeId = 'combTree' + 'treeMenu';
						$ztreeContent.append('<ul id="'+treeId+'" class="ztree" style="margin-top:0; "></ul>');
						$('body').append($ztreeContent);
						//加载树并默认展开第一个节点
						var nodeData = getTreeData(options);
						var treeObj = $.fn.zTree.init($('#'+treeId), setting, nodeData);
						var childNodes = treeObj.getNodes();
						if(childNodes) {
							treeObj.expandNode(childNodes[0], true); 
						}
						//设置文本框默认值
						setDefault();
						//设置下拉框容器坐标和宽度
						var $combTree = $('#'+comboxTreeId);
						$ztreeContent.css({left:($combTree.offset().left) + "px", top:$combTree.offset().top + $combTree.outerHeight() + "px", width: ($combTree.outerWidth())+"px"}).slideDown("fast");
					} else {
						$(".menuContent").remove();
					}
				}
				if ($(e.target).attr('class') != 'menuContent' &&
					e.target.id != comboxTreeId &&
					$(e.target).parents(".menuContent").length==0) {
					if( $(".menuContent").length != 0) {
						$(".menuContent").remove();
					}
				}
				$(document).scrollTop(0);
			})
		},
		getValue: function(){
			return this.attr('bind-data');
		},
		getText: function(){
			return this.val();
		}
	};
	
	var getTreeData = function(options){
		//return CHINA_REGIONS;
		var nodes = []; 
		/**
		 * 查询所有组织
		 */
		$.ajax({
			url : options.url,
			data: options.param,
			async : false,
			dataType : 'json',
			type : 'post',
			success : function(data) {
				var data = data.rows || data.data || data.list || data.result || data;
				if (data) {
					$.each(data, function(index, row) {
						nodes.push({
							id : row[options.idKey],
							pId : row[options.pIdKey],
							name : row[options.nameKey]
						});
						if (options.defaultValue == row[options.idKey]) {
							options.defaultText = row[options.nameKey];
						}
					});
				}
			}
		});
		return nodes;
	}
	
})(jQuery);